package com.zy.dingdong.activity;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.zy.dingdong.R;
import com.zy.dingdong.util.GlideBlurTransformation;
import com.zy.dingdong.util.OkHttpUtil;
import com.zy.dingdong.util.PictureUtil;
import com.zy.dingdong.util.RegexUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class MineActivity extends BaseActivity {

    private static final String TAG = "HELLO";
    private ImageView myImage;

    private RelativeLayout myImageBg;

    private TextView myName;

    private TextView titleText;
    private ImageView hasNew;
    private SimpleTarget bgTarget;

    private LinearLayout editMyself;
    private LinearLayout update_image;
    private LinearLayout support;
    private LinearLayout account;
    private LinearLayout logout;
    private PictureUtil pictureUtil;
    private String username;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.mine);

        titleText = findViewById(R.id.title_text);
        titleText.setText("个人中心");
        ImageView back = findViewById(R.id.back);
        back.setVisibility(View.GONE);
        hasNew = findViewById(R.id.has_new_message);
        hasNew.setVisibility(View.GONE);

        pictureUtil = new PictureUtil(MineActivity.this);
        username  = owner.getUsername();
        //设置背景图片
        myImage = findViewById(R.id.my_image);

        myImageBg = findViewById(R.id.my_image_bg);
        myName = findViewById(R.id.my_name);
        //功能
        editMyself = findViewById(R.id.edit_myself);
        update_image = findViewById(R.id.update_image);
        support = findViewById(R.id.support);
        account = findViewById(R.id.account);
        logout = findViewById(R.id.logout);

        myName.setText(owner.getName());

        bgTarget = new SimpleTarget() {
            @Override
            public void onResourceReady(Object resource, Transition transition) {
                myImageBg.setBackground((Drawable)resource);
            }
        };
        Uri uri = Uri.parse("https://picb.zhimg.com/v2-3740425599109fd793669bc8870c3109_r.jpg?source=1940ef5c");
        //设置默认背景图
        Glide.with(MineActivity.this)
                .load(uri)
                .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(this)))
                .into(bgTarget);

        //设置圆角图
        long time = System.currentTimeMillis();
        String timeFlag = "?time="+time;
        Glide.with(MineActivity.this)
                .load(NGINX_SERVER_URL+"/"+owner.getImageBase64()+timeFlag)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(myImage);
        //功能点击监听
        editMyself.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                editMyselfPanel();
                return false;
            }
        });
        //更新头像
        update_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] getPictureWays = new String[]{"相册", "相机"};
                AlertDialog dialog = new AlertDialog.Builder(MineActivity.this)
                        .setItems(getPictureWays, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int i) {
                                switch (i) {
                                    case 0:
                                        pictureUtil.openPictureLib();
                                        break;
                                    case 1:
                                        pictureUtil.openCamera();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }).create();
                dialog.show();
            }
        });
        //客服支持
        support.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                getSupport();
                return false;
            }
        });
        //账户安全
        account.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Toast.makeText(MineActivity.this,"账户安全",Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        //退出登录
        logout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                prefEditor.remove("ownerNetId");
                prefEditor.commit();
                Intent intent=new Intent("FORCE_OFFLINE");
                intent.putExtra("warringMsg","您将会退出叮咚");
                sendBroadcast(intent);
                return false;
            }
        });

    }
    private EditText myNewName;
    private EditText myNewAge;
    private EditText myNewCity;
    public void editMyselfPanel(){
        AlertDialog.Builder dialog = new AlertDialog.Builder(MineActivity.this);
        View view = LayoutInflater.from(this.getBaseContext()).inflate(R.layout.edit_myself,null,false);
        dialog.setView(view);
        dialog.setTitle("修改个人信息");
        myNewName = view.findViewById(R.id.my_new_name);
        myNewAge = view.findViewById(R.id.my_new_age);
        myNewCity = view.findViewById(R.id.my_new_city);
        dialog.setPositiveButton("确认修改", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String newName = myNewName.getText().toString();
                String newAge = myNewAge.getText().toString();
                String newCity = myNewCity.getText().toString();
                if (newName.equals("") || newAge.equals("") || !RegexUtil.isNumber(newAge) || newCity.equals("")){
                    Toast.makeText(MineActivity.this, "请完善信息", Toast.LENGTH_SHORT).show();
                }else{
                    Map params=new HashMap();
                    params.put("name",newName);
                    params.put("age",newAge);
                    params.put("city",newCity);
                    updateUserInfoRequest(params);
                }
            }
        });
        dialog.show();
    }

    public void getSupport(){
        AlertDialog.Builder dialog = new AlertDialog.Builder(MineActivity.this);
        dialog.setMessage("QQ:2978766226");
        dialog.show();
    }

    //更新信息
    private void updateUserInfoRequest(final Map paramMap){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = SERVER_URL+"/user/"+username+"/updateUserInfo";
                    String jsonStr = OkHttpUtil.synPost(url,paramMap);
                    updateUserInfoResponse(jsonStr);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void updateUserInfoResponse(final String jsonStr){
        MineActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Map jsonMap = JSON.parseObject(jsonStr);
                final String message = (String) jsonMap.get("message");
                if (message.equals("success")){
                    //信息完善，跳转到登录页面
                    Toast.makeText(MineActivity.this, "信息更新成功", Toast.LENGTH_LONG).show();
                    updateOwnerRequest(username);
                }else{
                    Toast.makeText(MineActivity.this, message, Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    //更新头像
    private void updateHeadImageRequest(final File file){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = SERVER_URL+"/user/"+username+"/updateHeadImage";
                    String jsonStr = OkHttpUtil.fileUpload(url,file);
                    Log.d(TAG, "updateHeadImageRequest: 更新头像");
                    updateHeadImageResponse(jsonStr);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void updateHeadImageResponse(final String jsonStr){
        MineActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Map jsonMap = JSON.parseObject(jsonStr);
                final String message = (String) jsonMap.get("message");
                if (message.equals("success")){
                    //更新后更新本地owner信息
                    updateOwnerRequest(username);
                    //信息完善，跳转到登录页面
                    Toast.makeText(MineActivity.this, "头像更新成功", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(MineActivity.this, message, Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    //更新本地Owner信息
    private void updateOwnerRequest(final String username){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = LoginActivity.SERVER_URL + "/user/searchUser/"+ username;
                    String jsonStr = OkHttpUtil.synGet(url);
                    updateOwnerResponse(jsonStr);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void updateOwnerResponse(final String jsonStr){
        MineActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Map jsonMap = JSON.parseObject(jsonStr);
                final String message = (String) jsonMap.get("message");
                if (message.equals("success")){
                    //进行本地存储
                    JSONObject data = (JSONObject) jsonMap.get("data");
                    owner.setImageBase64(data.getString("imagePath"));
                    owner.setName(data.getString("name"));
                    refreshUI();
                }
                else {
                    Toast.makeText(MineActivity.this,"本地owner信息更新失败",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    //更新数据后刷新UI页面
    private void refreshUI(){
        //注意Glide会有缓存，当URL不变时，会请求缓存
        //设置背景图
        /*Glide.with(MineActivity.this)
                .load(NGINX_SERVER_URL+"/"+ owner.getImageBase64())
                .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(this)))
                .into(bgTarget);*/
        //获取时间戳，用于更新Url，解决记在Glide缓存图片的问题
        long time = System.currentTimeMillis();
        String timeFlag = "?time="+time;
        //设置圆角图
        Glide.with(MineActivity.this)
                .load(NGINX_SERVER_URL+"/"+ owner.getImageBase64()+timeFlag)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(myImage);
        myName.setText(owner.getName());
        Log.d(TAG, "refreshUI: 视图更新函数被调用----");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d(TAG, "MineActivity: 打开相册后的回调方法：" + data.toString());
        if (data.getData() == null){
            Toast.makeText(MineActivity.this,"未选择图片",Toast.LENGTH_SHORT).show();
        }else {
            super.onActivityResult(requestCode, resultCode, data);
            pictureUtil.showPicture(requestCode, resultCode, data, MineActivity.this,myImage);
            File newHeadImage = pictureUtil.getPictureFile();
            if (newHeadImage != null) {
                Log.d(TAG, "update_image onClick: 更新头像");
                updateHeadImageRequest(newHeadImage);
            }
            else
                Toast.makeText(MineActivity.this,"更新头像失败",Toast.LENGTH_SHORT).show();
        }
    }

    //请求权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //申请相机权限
        if (requestCode == PictureUtil.CAPTURE_PERMISSION){
            if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                //执行拍照
                pictureUtil.doTake();
            } else{
                Toast.makeText(this,"你没有获得相机的权限",Toast.LENGTH_SHORT).show();
            }
        }
        //申请读取内存的权限
        else if (requestCode == PictureUtil.PICTURE_LIB_PERMISSION){
            if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                //执行从相册选取图片
                pictureUtil.openAlbum();
            } else{
                Toast.makeText(this,"你没有获得访问相册的权限",Toast.LENGTH_LONG).show();
            }
        }
    }
}
